<template>
  <div class="pageOut">
    <div class="pageIn">
      <el-form :inline="true" :model="formSearch" size="small">
        <el-form-item>
          <el-input
            v-model="formSearch.discount_name"
            placeholder="搜索优惠券名称"
            clearable
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="formSearch.time"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button icon="el-icon-search" @click="search">查询</el-button>
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="handleAdd"
            v-show="permission.add"
            >新增优惠券</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        border
        ref="table"
        :height="height - 170"
        :data="tableData"
        :header-cell-style="{ background: '#FAFAFA', color: '#606266' }"
        v-loading="loading"
        element-loading-background="rgba(255, 255, 255, 0.5)"
        style="width: 100%"
      >
        <!-- <el-table-column prop="id" width="100" label="序号"></el-table-column> -->
        <el-table-column
          :show-overflow-tooltip="tooltip"
          prop="couponName"
          label="优惠券名称"
        ></el-table-column>
        <el-table-column prop="fullPrice" label="使用最低价格">
        </el-table-column>
        <el-table-column
          prop="reducePrice"
          :show-overflow-tooltip="tooltip"
          label="优惠价格"
        ></el-table-column>
        <el-table-column
          prop="maxQuantity"
          :show-overflow-tooltip="tooltip"
          label="最大发放数量"
        ></el-table-column>

        <el-table-column
          prop="mainPicture"
          width="159"
          label="优惠券图片"
          align="center"
        >
          <template slot-scope="scope">
            <div class="img" style="cursor: pointer">
              <viewer>
                <img
                  :src="scope.row.mainPicture"
                  alt
                  :onerror="errImg"
                  title="查看高清图片"
                  style="width: 40px; height: 40px; border-radius: 50%"
                />
              </viewer>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="commodity"
          label="适用商品"
          :show-overflow-tooltip="tooltip"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="checkShop(scope.row, '1')"
              >点击查看</el-link
            >
          </template>
        </el-table-column>

        <el-table-column
          prop="effective_time"
          label="有效时间"
          :show-overflow-tooltip="tooltip"
        ></el-table-column>
        <el-table-column
          prop="create_time"
          label="添加时间"
          :show-overflow-tooltip="tooltip"
        ></el-table-column>
        <el-table-column
          prop="commodity"
          label="优惠券说明"
          :show-overflow-tooltip="tooltip"
        >
          <template slot-scope="scope">
            <el-link type="primary" @click="editorClick(scope.row)"
              >查看详情</el-link
            >
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              v-show="permission.GrantData"
              size="mini"
              @click="grantClick(scope.row)"
              >发放使用情况</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handleEdit(scope.row)"
              v-show="permission.edit"
              >编辑</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row.id)"
              v-show="permission.del"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 优惠券添加和优惠券编辑 -->
      <el-drawer
        size="400px"
        :title="type === 'add' ? '添加优惠券' : '修改优惠券'"
        :visible.sync="visible"
        @close="onCancel('ruleForm')"
        custom-class="custom_drawer"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          label-position="top"
          ref="ruleForm"
          size="mini"
          label-width="120px"
          class="form-drawer__main"
        >
          <el-form-item
            label="优惠券名称"
            prop="discount_name"
            style="margin-bottom: 30px"
          >
            <el-input
              clearable
              v-model="ruleForm.discount_name"
              placeholder="请输入优惠券名称"
              style="width: 250px"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="优惠券图片"
            prop="image"
            style="margin-bottom: 30px"
          >
            <UploadImage
              @getImgSrc="getImgSrc"
              :imageUrl.sync="ruleForm.image"
            />
          </el-form-item>
          <el-form-item label="适用商品">
            <el-button type="primary" @click="checkShop(commodityCheck, '2')"
              >请选择</el-button
            >
          </el-form-item>
          <div>
            <el-tag
              v-for="(tag, tagIndex) in commodityCheck"
              @close="closeTag(tagIndex, tag)"
              :key="tagIndex"
              closable
              style="margin: 2px 10px 0px 0px"
            >
              <span class="tagBox">{{ tag.name }}</span>
            </el-tag>
          </div>
          <el-form-item
            label="使用最低价格"
            prop="min_price"
            style="margin-bottom: 30px"
          >
            <el-input
              @mousewheel.native.prevent
              clearable
              @blur="clearMinus($event, 'min_price')"
              type="number"
              v-model.number="ruleForm.min_price"
              placeholder="请输入最低价格"
            >
              <span slot="append">元</span>
            </el-input>
          </el-form-item>
          <el-form-item
            label="优惠金额"
            prop="max_price"
            style="margin-bottom: 30px"
          >
            <el-input
              @mousewheel.native.prevent
              clearable
              @blur="clearMinus($event, 'max_price')"
              type="number"
              v-model.number="ruleForm.max_price"
              placeholder="请输入优惠金额"
            >
              <span slot="append">元</span>
            </el-input>
          </el-form-item>

          <el-form-item
            label="最大发放数量"
            prop="money"
            style="margin-bottom: 30px"
          >
            <el-input
              @mousewheel.native.prevent
              clearable
              @blur="clearMinus($event, 'money')"
              type="number"
              v-model.number="ruleForm.money"
              placeholder="请输入最大发放数量"
            >
            </el-input>
          </el-form-item>

          <el-form-item
            label="有效期"
            prop="end_time"
            style="margin-bottom: 30px"
          >
            <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="ruleForm.end_time"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              clearable
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item
            label="添加时间"
            prop="addTime"
            style="margin-bottom: 30px"
          >
            <el-date-picker
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              v-model="ruleForm.addTime"
              placeholder="选择添加时间"
            >
            </el-date-picker>
          </el-form-item> -->
          <el-form-item
            label="优惠券说明"
            prop="content"
            style="margin-bottom: 30px"
          >
            <Editor
              @onEditorChange="onEditorChange"
              :content="ruleForm.content"
              ref="editor"
            />
          </el-form-item>
        </el-form>
        <div class="form-drawer__footer" style="width: 400px">
          <el-button @click="onCancel('ruleForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="onConfirm('ruleForm')"
            :loading="confirmLoading"
            >{{ confirmLoading ? "提交中 ..." : "确 定" }}</el-button
          >
        </div>
      </el-drawer>
      <el-dialog
        append-to-body
        title="适用商品"
        :visible.sync="aggregateVisible"
        width="60%"
        @close="closeChange"
        top="10vh"
      >
        <el-form :inline="true" label-width="auto" :model="comForm">
          <el-form-item label="商品名" prop="commodityName">
            <el-input
              maxlength="20"
              size="small"
              v-model="comForm.commodityName"
              placeholder="请输入内容"
              clearable
              @clear="comSearch"
            ></el-input>
          </el-form-item>
          <el-form-item label-width="20px">
            <el-button type="primary" size="small" @click="comSearch"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          ref="aggTable"
          @selection-change="handleSelectionChange"
          :data="commodityTableData"
          height="500"
        >
          <el-table-column v-if="typeNum != '1'" type="selection" width="55">
          </el-table-column>
          <el-table-column label="商品图" prop="mainPicture">
            <template slot-scope="scope">
              <img
                :src="scope.row.mainPicture"
                width="50px"
                height="50px"
                alt=""
                srcset=""
              />
            </template>
          </el-table-column>
          <el-table-column
            label="商品名"
            :show-overflow-tooltip="tooltip"
            prop="name"
          ></el-table-column>
          <el-table-column
            label="商品类目"
            prop="goodsTypeName"
          ></el-table-column>
          <el-table-column label="售价" prop="sellingPrice"></el-table-column>
        </el-table>
        <div class="pagination">
          <!-- <el-pagination
            background
            @size-change="comHandleSizeChange"
            @current-change="comHandleCurrentChange"
            :current-page="comPageNumber"
            :page-size="comPageSize"
            layout="total, prev, pager, next, jumper"
            :total="comTotal"
          ></el-pagination> -->
        </div>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="aggregateVisible = false">取 消</el-button> -->
          <el-button type="primary" @click="aggregateClick">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        append-to-body
        title="优惠券说明"
        :visible.sync="coupoDeis"
        width="50%"
        @colse="editorColse"
      >
        <Editor
          @onEditorChange="onEditorChange"
          :content="ruleForm.content"
          :disabled="true"
          ref="editor"
        />

        <span slot="footer" class="dialog-footer">
          <el-button @click="coupoDeis = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  couponList,
  couponAdd,
  couponEdit,
  coupoDel,
  MAIN,
  goodsSel,
  couponDetail,
} from "../../utils/api";
import UploadImage from "../../components/UploadImage";
import Editor from "../../components/Editor";
export default {
  name: "DiscountList",
  props: ["height"],
  components: {
    UploadImage,
    Editor,
  },
  data() {
    return {
      tableData: [],
      commodityType: "",
      userList: [],
      commodityCheck: [],
      aggregateVisible: false,
      commodityTableData: [],
      tooltip: true, //内容过长被隐藏时显示 tooltip
      loading: true, //显示加载表格
      pageSize: 10, //每页多少条
      currentPage: 1, //当前第几页
      pageSizes: [10, 20, 30, 40, 50], //每页选择条数
      total: 0, //共多少条
      errImg: 'this.src="' + require("../../../static/img/user.png") + '"',
      permission: {
        add: false,
        edit: false,
        del: false,
        GrantData: false,
      }, //权限

      detailData: {},
      comPageNumber: 1,
      comPageSize: 500,
      comTotal: 1,
      formSearch: {
        discount_name: "",
        time: "",
      }, //搜索
      //编辑弹窗
      visible: false,
      confirmLoading: false,
      type: "",
      memberId: "",
      currentRow: {}, //当前行数据信息
      typeNum: "",
      ruleForm: {
        discount_name: "",
        max_price: "",
        min_price: "",
        money: "",
        image: "",
        end_time: "",
        content: "",
        addTime: "",
      }, //添加和修改的表单
      comForm: {
        commodityName: "",
      },
      coupoDeis: false, //优惠券说明弹窗
      userInfo: {},
      rules: {
        discount_name: [
          { required: true, message: "请输入优惠券名称", trigger: "blur" },
        ],
        max_price: [
          { required: true, message: "请输入优惠金额", trigger: "blur" },
        ],
        min_price: [
          { required: true, message: "请输入使用最低价格", trigger: "blur" },
        ],
        money: [
          { required: true, message: "请输入最大发放数量", trigger: "blur" },
        ],
        // deduction_price: [
        //   { required: true, message: "请输入抵扣价格无门槛", trigger: "blur" },
        // ],
        end_time: [
          { required: true, message: "请选择有效期", trigger: "blur" },
        ],
        addTime: [
          { required: true, message: "请选择添加时间", trigger: "change" },
        ],
        image: [{ required: true, message: "请选择图片", trigger: "change" }],
      },
    };
  },

  mounted() {
    this.getResource();
    if (this.$route.query.memberId) {
      this.memberId = this.$route.query.memberId;
      this.getData();
    }
    this.getCommodity();
  },
  methods: {
    //富文本框
    onEditorChange(e) {
      this.ruleForm.content = e;
    },
    // 标签删除
    closeTag(index, item) {
      this.commodityCheck.splice(index, 1);

      this.$refs.aggTable.toggleRowSelection(item, false);
    },
    checkShop(rows, type) {
      this.typeNum = type;
      this.aggregateVisible = true;
      // 查看详情
      if (type == 1) {
        this.currentRow = rows;

        this.getCommodity(rows.id);
        // 添加 编辑
      } else if (type == "2") {
        if (this.type == "add") {
          if (rows) {
            rows.forEach((row) => {
              this.$refs.aggTable.toggleRowSelection(row);
            });
          } else {
            this.$refs.aggTable.clearSelection();
          }
          this.getCommodity();
        } else {
          // this.getCommodity();

          // this.$refs.aggTable.toggleAllSelection(false);
          // 编辑
          setTimeout(() => {
            this.commodityCheck.map((v) => {
              this.$refs.aggTable.toggleRowSelection(v, true);
            });
          }, 500);
        }
      }
    },
    getResource() {
      // console.log(this.$route.name);
      this.loading = true;
      const userinfo = JSON.parse(sessionStorage.getItem("userInfo")); //解密,获取用户登录信息
      this.userInfo = userinfo;
      let arr = userinfo.menu_id.split(",");
      // 新增 48
      // 发放使用情况 89
      // 编辑 49
      // 删除 50

      if (arr.indexOf("48") > -1) {
        this.permission.add = true;
      }
      if (arr.indexOf("49") > -1) {
        this.permission.edit = true;
      }
      if (arr.indexOf("50") > -1) {
        this.permission.del = true;
      }
      if (arr.indexOf("89") > -1) {
        this.permission.GrantData = true;
      }
      this.getData();
    },
    //清除输入框负数
    clearMinus(e, type) {
      let boolean = new RegExp("^[0-9][0-9.]*$").test(e.target.value);
      if (!boolean) {
        e.target.value = "";
        if (type === "max_price") this.ruleForm.max_price = "";
        if (type === "min_price") this.ruleForm.min_price = "";
        if (type === "money") this.ruleForm.money = "";
        if (type === "deduction_price") this.ruleForm.deduction_price = "";
      }
    },

    editorClick(row) {
      this.coupoDeis = true;
      this.postRequest(couponDetail, { id: row.id }, MAIN).then((res) => {
        if (res.code === 200) {
          this.ruleForm.content = res.data.description;
        }
      });
    },
    // 发放使用情况
    grantClick(row) {
      let params = {
        row,
        key: "DiscountList",
      };
      window.sessionStorage.setItem(params.key, JSON.stringify(params));
      this.$router.push("/GrantData");
    },

    comSearch() {
      this.comPageNumber = 1;
      if (this.type == "") {
        this.getCommodity(this.currentRow.id);
      } else {
        this.getCommodity();
      }
    },
    getImgSrc(e) {
      this.ruleForm.image = e;
    },
    // 获取适用商品
    getCommodity(id) {
      let params = {
        name: this.comForm.commodityName,
        pageNumber: this.comPageNumber,
        pageSize: this.comPageSize,
        couponId: id ? id : "",
      };
      this.postRequest(goodsSel, params, MAIN).then((res) => {
        if (res.code == 200) {
          this.commodityTableData = res.data.list;
          this.comTotal = res.data.count;

          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.aggTable) this.$refs.aggTable.doLayout();
          });
        }
      });
    },
    aggregateClick() {
      // console.log(this.commodityCheck);
      this.aggregateVisible = false;
    },
    //获取初始数据
    getData() {
      this.loading = true;
      let start_time, end_time;
      if (this.formSearch.time != "" && this.formSearch.time != null) {
        start_time = this.formSearch.time[0];
        end_time = this.formSearch.time[1];
      }
      let params = {
        couponName: this.formSearch.discount_name,
        start_time,
        end_time,
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        memberId: this.memberId,
      };
      this.postRequest(couponList, params, MAIN).then((res) => {
        if (res.code == 200) {
          // console.log(res);
          this.tableData = res.data.list;
          this.total = res.data.count;
          this.loading = false;

          this.$nextTick(() => {
            //避免表格表头样式错乱
            if (this.$refs.table) this.$refs.table.doLayout();
          });
        }
      });
    },
    //分页
    comHandleSizeChange(val) {
      //每页 ${val} 条
      this.comPageSize = val;
      this.getCommodity();
    },
    comHandleCurrentChange(val) {
      //当前页
      this.comPageNumber = val;
      this.getCommodity();
    },

    //分页
    handleSizeChange(val) {
      //每页 ${val} 条
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      //当前页
      this.currentPage = val;
      this.getData();
    },
    //查询
    search() {
      this.getData();
    },
    //新增
    handleAdd() {
      this.type = "add";
      this.currentRow = {};
      this.visible = true;
    },
    handleSelectionChange(val) {
      this.commodityCheck = val;
    },
    closeChange() {
      if (this.typeNum == 1) {
        this.getCommodity();
      }
      this.comForm.commodityName = "";
      this.typeNum = "";
      // if (rows) {
      //   rows.forEach((row) => {
      //     this.$refs.aggTable.toggleRowSelection(row);
      //     console.log(row);
      //   });
      // } else {
      //   this.$refs.aggTable.clearSelection();
      // }
      // console.log(this.commodityCheck);
    },
    //编辑
    handleEdit(row) {
      this.type = "edit";
      this.currentRow = row;
      this.visible = true;
      this.postRequest(couponDetail, { id: row.id }, MAIN).then((res) => {
        if (res.code === 200) {
          this.detailData = res.data;
          this.goods = res.data.goods;
          this.commodityCheck = [];
          this.goods.split(",").forEach((v) => {
            let index = this.commodityTableData.findIndex((item) => {
              return v == item.id;
            });
            if (index != -1) {
              this.commodityCheck.push(this.commodityTableData[index]);
            }
          });
          this.ruleForm = {
            discount_name: row.couponName,
            max_price: row.reducePrice,
            min_price: row.fullPrice,
            money: row.maxQuantity,
            image: row.mainPicture,
            content: row.content || "",
            end_time: row.effective_time.split("~"),
            addTime: row.create_time,
          };
        }
      });
    },
    //删除
    handleDel(id) {
      let parm = {
        id: id,
        userId: this.userInfo.id,
      };
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.postRequest(coupoDel, parm, MAIN).then((res) => {
            // console.log(res);
            if (res.code == 200) {
              this.$notify({
                title: "删除成功",
                message: res.msg,
                type: "success",
              });
              this.getData();
            }
          });
        })
        .catch(() => {});
    },

    onConfirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          // setTimeout(() => this.onCancel(formName), 1000);
          if (this.type == "add") {
            this.addDiscount();
          } else if (this.type == "edit") {
            this.editDiscount();
          }
        } else {
          return false;
        }
      });
    },
    // 添加
    addDiscount() {
      if (this.commodityCheck.length == 0) {
        this.confirmLoading = false;

        return this.$notify.error("请选择适用商品");
      }
      let goods = [];

      this.commodityCheck.forEach((v) => {
        goods.push(v.id);
      });
      let params = {
        couponName: this.ruleForm.discount_name,
        reducePrice: this.ruleForm.max_price,
        fullPrice: this.ruleForm.min_price,
        maxQuantity: this.ruleForm.money,
        mainPicture: this.ruleForm.image,
        start_time: this.ruleForm.end_time[0],
        end_time: this.ruleForm.end_time[1],
        description: this.ruleForm.content,
        create_time: this.ruleForm.addTime,
        userId: this.userInfo.id,
        goods: goods.join(","),
      };
      this.postRequest(couponAdd, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "添加成功",
            message: res.msg,
            type: "success",
          });
        }
        this.confirmLoading = false;

        this.onReset();
        this.getData();
      });
    },
    // 编辑
    editDiscount() {
      if (this.goods == "" && this.commodityCheck.length == 0)
        return this.$notify.error("请选择适用商品");
      let goods = [];

      this.commodityCheck.forEach((v) => {
        goods.push(v.id);
      });
      let params = {
        id: this.currentRow.id,
        couponName: this.ruleForm.discount_name,
        reducePrice: this.ruleForm.max_price,
        fullPrice: this.ruleForm.min_price,
        maxQuantity: this.ruleForm.money,
        mainPicture: this.ruleForm.image,
        start_time: this.ruleForm.end_time[0],
        end_time: this.ruleForm.end_time[1],
        description: this.ruleForm.content,
        create_time: this.ruleForm.addTime,
        userId: this.userInfo.id,
        goods: goods ? goods.join(",") : this.goods,
      };

      this.postRequest(couponEdit, params, MAIN).then((res) => {
        // console.log(res);
        if (res.code == 200) {
          this.$notify({
            title: "编辑成功",
            message: res.msg,
            type: "success",
          });
        }
        this.onReset();
        this.getData();
      });
    },
    onCancel(formName) {
      this.$refs[formName].resetFields();
      this.onReset();
      this.$refs.aggTable.clearSelection();
    },
    editorColse() {
      if (this.$refs.editor) this.$refs.editor.clear();
    },
    //清空重置表单
    onReset() {
      if (this.$refs.editor) this.$refs.editor.clear();

      this.visible = false;
      this.confirmLoading = false;
      this.commodityCheck = [];
      this.type = "";
      this.ruleForm = {
        discount_name: "",
        type: "",
        max_price: "",
        min_price: "",
        money: "",
        deduction_price: "",
        image: "",
        end_time: "",
        content: "",
      };
    },
  },
};
</script>

<style scoped>
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1890ff;
  color: #fff;
  cursor: pointer;
}
/deep/ .el-input--mini .el-input__inner {
  height: 32px;
  line-height: 32px;
}
/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
/deep/ input[type="number"] {
  -moz-appearance: textfield;
}
.tagBox {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.el-tag /deep/ .el-icon-close {
  top: -11px;
}
</style>
